﻿using System;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Interactivity;
using System.Windows.Media;
using System.Windows.Media.Imaging;

using Rio.Framework.Localisation;
using Rio.Manager.Application.Utils.Image;

namespace Rio.Manager.Application.Behaviors
{
    public class ExportReportBehavior : Behavior<Button>
    {
        #region Fields

        public static readonly DependencyProperty UIElementToExportProperty = 
            DependencyProperty.Register("UIElementToExport", typeof(UIElement), typeof(ExportReportBehavior), null);

        #endregion Fields

        #region Constructors

        public ExportReportBehavior()
            : base()
        {
        }

        #endregion Constructors

        #region Properties

        public UIElement UIElementToExport
        {
            get { return (UIElement)GetValue(UIElementToExportProperty); }
            set { SetValue(UIElementToExportProperty, value); }
        }

        #endregion Properties

        #region Methods

        /// <summary>
        /// Called when [attached].
        /// </summary>
        protected override void OnAttached()
        {
            base.OnAttached();
            this.AssociatedObject.Click += AssociatedObject_Click;
        }

        /// <summary>
        /// Called when [detaching].
        /// </summary>
        protected override void OnDetaching()
        {
            base.OnDetaching();
            this.AssociatedObject.Click -= AssociatedObject_Click;
        }

        /// <summary>
        /// Handles the Click event of the AssociatedObject control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
        private void AssociatedObject_Click(object sender, RoutedEventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.DefaultExt = "png";
            saveFileDialog.Filter = "PNG Files | *.png";

            if (saveFileDialog.ShowDialog() == true)
            {
                using (Stream memoryStream = saveFileDialog.OpenFile())
                {
                    (UIElementToExport as StackPanel).Background = new SolidColorBrush(Colors.White);

                    WriteableBitmap writeableBitmap = new WriteableBitmap(UIElementToExport, null);

                    int width = writeableBitmap.PixelWidth;
                    int height = writeableBitmap.PixelHeight;

                    // Create an EditableImage for encoding
                    EditableImage ei = new EditableImage(width, height);

                    // Transfer pixels from the WriteableBitmap to the EditableImage
                    for (int i = 0; i < height; i++)
                    {
                        for (int j = 0; j < width; j++)
                        {
                            int pixel = writeableBitmap.Pixels[(i * width) + j];
                            ei.SetPixel(j, i,
                                        (byte)((pixel >> 16) & 0xFF),   // R
                                        (byte)((pixel >> 8) & 0xFF),    // G
                                        (byte)(pixel & 0xFF),           // B
                                        (byte)((pixel >> 24) & 0xFF)    // A
                            );
                        }
                    }

                    int len = 0;
                    byte[] bytes = null;

                    // Generate a PNG stream from the EditableImage and convert to byte[]
                    using (Stream png = ei.GetStream())
                    {
                        len = (int)png.Length;
                        bytes = new byte[len];
                        png.Read(bytes, 0, len);
                    }

                    // Write the PNG
                    memoryStream.Write(bytes, 0, len);

                    (UIElementToExport as StackPanel).Background = new SolidColorBrush(Colors.Transparent);

                    MessageBox.Show(Resx.GetLabel(ResxRioManager.REPORT_CLOSE_MSG), String.Empty, MessageBoxButton.OK);
                }
            }
        }

        #endregion Methods
    }
}